<style lang="less">

</style>
<template>
  <div @click="op">
    {{is_end?'已结束':(is_sold_out?'已售完':btnStr)}}
  </div>
</template>
<script>
  import Vue from 'vue';
  import {Button} from 'vant';
  import {createKanJiaOrder} from "@/api/kanjia";

  const OP_JOIN = 0;
  const OP_NONE = -1;
  const OP_TO_CREATE_ORDER = 2;

  Vue.use(Button);
  export default {
    name: 'kanjia-op-button',
    props: {
      goods_id: {type: Number, default: -1},//
      sku_id: {type: Number, default: -1},//
      is_end: {type: Boolean, default: false},//是否结束
      is_sold_out: {type: Boolean, default: false},//是否售完
      kanjia_data: {type: String, default: ''}//砍价信息
    },
    data() {
      return {
        btnStr: '立即参加',
        opType: 0,//操作
	      kjData:null
      };
    },
    watch: {
      'is_end': {
        handler(n, o) {
          if (n) {
            this.btnStr = '已结束';
          }
        }
      },
      'is_sold_out': {
        handler(n, o) {
          if (n) {
            this.btnStr = '已售完';
          }
        }
      },
      'kanjia_data': {
        handler(n, o) {
          let val = JSON.parse(n);
          this.kjData = val;
          if (val === null) {
            this.btnStr = '立即参加';
            this.opType = OP_JOIN;
          } else {
            //两种情况，一种是自己参加的，一种是别人参加的
            if (val.uid === this.$store.state.user.userInfo.id) {
              if (val.lowest_price === val.current_price) {
                this.btnStr = '立即付款';
                this.opType = OP_TO_CREATE_ORDER;
              } else {
                this.btnStr = '现价购买';
                this.opType = OP_TO_CREATE_ORDER;
              }
            } else {
              this.btnStr = '我也参加';
              this.opType = OP_JOIN;
            }
          }
        },
        deep: true,
        immediate: true
      },
    },
    methods: {
      op() {
        if(this.is_end||this.is_sold_out){
          return;
        }
        if (this.opType === OP_JOIN) {
          let vm = this;
          createKanJiaOrder(vm.goods_id, vm.sku_id).then(rep => {
            this.$emit('kj-refresh');
          })
        } else if (this.opType === OP_TO_CREATE_ORDER) {
          this.$emit('kj-submit', this.kjData.id)
        }
      }
    }

  }
</script>